package com.vanguard.client;

import com.vanguard.codec.ClientCharsetCodecFactory;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.ReadFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.session.IoSessionConfig;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * @Title: mina客户端
 * @Description:
 * @Author: vanguard
 * @Version: 1.0
 * @Date: 2018/12/25
 */
public class MinaClient {
    private static Logger logger = LoggerFactory.getLogger(MinaClient.class);

    private String host;
    private int port;
    private String charset;

    public MinaClient(String host, int port, String charset) {
        this.host = host;
        this.port = port;
        this.charset = charset;
    }

    public String send(String message) {
        // 创建一个socket连接
        IoConnector connector = new NioSocketConnector();
        // 设置链接超时时间
        connector.setConnectTimeoutMillis(2000);
        //消息类型
        String messageType = "";

        //根据消息判断消息类型
        switch (message) {
            case "14":
                messageType = "FixedLength";
                break;
            case "11":
                messageType = "UserDefinedTailed";
                break;
            case "13":
                messageType = "NotFixedLength";
                break;
            default:

        }

        // 获取过滤器链
        DefaultIoFilterChainBuilder filterChain = connector.getFilterChain();
        // 添加编码过滤器 处理乱码、编码问题
        filterChain.addLast("codec", new ProtocolCodecFilter(new ClientCharsetCodecFactory(messageType, charset)));

        IoSession session = null;

        ConnectFuture future = null;

        try {
            // 消息核心处理器
            connector.setHandler(new MinaClientHandler());

            IoSessionConfig cfg = connector.getSessionConfig();
            //配置用户可读
            cfg.setUseReadOperation(true);

            // 创建连接
            future = connector.connect(new InetSocketAddress(host, port));
            // 等待连接创建完成
            future.awaitUninterruptibly();
            // 获得session
            session= future.getSession();
        } catch (Exception e) {
            logger.error("客户端链接异常...", e);
        }
        // 发送消息
        session.write(message);
        ReadFuture readFuture = session.read();
        //等待接收message
        readFuture.awaitUninterruptibly();
        Object respData = readFuture.getMessage();
        connector.dispose();
        logger.info("客户端连接关闭");
        return respData==null ? "CONNECT_TO_SERVER_ERROR" : respData.toString();
    }

}
